package com.fine.hair.manage.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fine.hair.comm.dto.ItemDto;
import com.fine.hair.comm.dto.ItemListDto;
import com.fine.hair.comm.utils.ApiResponse;
import com.fine.hair.comm.model.Item;
import com.fine.hair.manage.mapper.ItemMapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>项目控制层</p>
 *
 * @author mouseyCat
 * @date 2020/10/24 16:13
 */
@Api(tags = {"项目相关接口"})
@RestController
@RequestMapping("/item/")
public class ItemController {

    @Resource
    private ItemMapper itemMapper;

    @Autowired
    private Snowflake snowflake;

    @PutMapping("alter-item")
    @ApiOperation("修改项目")
    public ApiResponse alterItem(@RequestBody ItemDto dto) {
        Item item = itemMapper.selectById(dto.getItemId());
        BeanUtil.copyProperties(dto, item);
        itemMapper.updateById(item);
        return ApiResponse.ofSuccess();
    }

    @DeleteMapping("del-item/{itemId}")
    @ApiOperation("删除项目")
    public ApiResponse delItem(@PathVariable String itemId) {
        itemMapper.deleteById(itemId);
        return ApiResponse.ofSuccess();
    }

    @PostMapping("add-item")
    @ApiOperation("添加项目")
    public ApiResponse addItem(@RequestBody ItemDto dto) {
        Item item = new Item();
        item.setId(snowflake.nextId());
        BeanUtil.copyProperties(dto, item);
        item.setBranchId(Long.valueOf(dto.getBranchId()));
        itemMapper.insert(item);
        return ApiResponse.ofSuccess();
    }

    @PostMapping("item-list")
    @ApiOperation(value = "门店下的项目列表", notes = "不需要分页")
    public ApiResponse<List<Item>> itemList(@RequestBody ItemListDto dto) {
        if (StrUtil.isNotBlank(dto.getBranchId())) {
            List<Item> items = itemMapper.selectList(new LambdaQueryWrapper<Item>().eq(Item::getBranchId, dto.getBranchId()));
            items.addAll(itemMapper.selectList(new LambdaQueryWrapper<Item>().eq(Item::getBranchId, 0)));
            return ApiResponse.ofSuccess(items);
        } else {
            return ApiResponse.ofSuccess(itemMapper.selectList(new LambdaQueryWrapper<>()));
        }
    }
}
